package top.broncho.gank.ui.fragment

import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import androidx.fragment.app.viewModels
import top.broncho.gank.R
import top.broncho.gank.databinding.FragmentShareArticleBinding
import top.broncho.gank.utils.DialogUtil
import kotlinx.android.synthetic.main.fragment_share_article.*
import org.jetbrains.anko.design.snackbar
import top.broncho.mvvm.base.BaseDiFragment

/**
 * @author chenxz
 * @date 2019/11/15
 * @desc 分享文章
 */
class ShareArticleFragment : BaseDiFragment<FragmentShareArticleBinding>() {

    companion object {
        fun getInstance(): ShareArticleFragment = ShareArticleFragment()
    }


    private val viewModel by viewModels<ShareArticleViewModel> { viewModelFactory }

    private val mDialog by lazy {
        DialogUtil.getWaitDialog(activity!!, getString(R.string.submit_ing))
    }

    fun getArticleTitle(): String = et_article_title.text.toString().trim()

    fun getArticleLink(): String = et_article_link.text.toString().trim()


    override fun getLayoutId(): Int = R.layout.fragment_share_article

    fun showLoading() {
        mDialog.setCancelable(false)
        mDialog.setCanceledOnTouchOutside(false)
        mDialog.show()
    }

    fun hideLoading() {
        mDialog.dismiss()
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView(view)
        viewModel.shareArticle.observe({ lifecycle }) {
            showShareArticle(it.isSuccess)
        }
    }

    fun initView(view: View) {
        // 在fragment中使用 onCreateOptionsMenu 时需要在 onCrateView 中添加此方法，否则不会调用
        setHasOptionsMenu(true)
    }


    fun showShareArticle(success: Boolean) {
        if (success) {
            binding.etArticleLink.snackbar(getString(R.string.share_success))
//            EventBus.getDefault().post(RefreshShareEvent(true))
            activity?.finish()
        }
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        inflater.inflate(R.menu.menu_share_article, menu)
        super.onCreateOptionsMenu(menu, inflater)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.action_share_article -> {
                viewModel.shareArticle(getArticleMap())
            }
        }
        return super.onOptionsItemSelected(item)
    }

    private fun getArticleMap(): MutableMap<String, Any> {
        val map = mutableMapOf<String, Any>()
        map["title"] = getArticleTitle()
        map["link"] = getArticleLink()
        return map
    }

}